/**
* author: SamWu
* email：samwulqy@gmail.com
**/
<?php
header('Content-Type: application/json');
require_once '../includes/database.php';
require_once '../includes/security.php';

$response = ['success' => false, 'received' => false];

try {
    // 验证签名
    $signature = $_SERVER['HTTP_X_CALLBACK_SIGNATURE'] ?? '';
    $rawData = file_get_contents('php://input');
    
    if (!verifyCallbackSignature($rawData, $signature)) {
        throw new Exception('Invalid signature', 403);
    }
    
    $data = json_decode($rawData, true);
    if (!$data) {
        throw new Exception('Invalid callback data', 400);
    }
    
    // 验证必要字段
    $required = ['vuid', 'domain', 'token', 'result', 'timestamp', 'ip_address'];
    foreach ($required as $field) {
        if (!isset($data[$field])) {
            throw new Exception("Missing required field: $field", 400);
        }
    }
    
    // 获取网站的ID
    $stmt = $pdo->prepare("SELECT id FROM websites WHERE vuid = ?");
    $stmt->execute([$data['vuid']]);
    $website = $stmt->fetch();
    
    if (!$website) {
        throw new Exception('Invalid VUID', 404);
    }
    
    // 记录回调结果
    $stmt = $pdo->prepare("INSERT INTO verification_callbacks 
                          (website_id, token, result, ip_address, score, raw_data) 
                          VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->execute([
        $website['id'],
        $data['token'],
        $data['result'],
        $data['ip_address'],
        $data['score'] ?? null,
        $rawData
    ]);
    
    // 更新统计
    if ($data['result'] === 'failed') {
        $stmt = $pdo->prepare("UPDATE request_stats 
                              SET failed_attempts = failed_attempts + 1 
                              WHERE website_id = ? AND current_month = ?");
        $stmt->execute([$website['id'], date('Ym')]);
    }
    
    $response = [
        'success' => true,
        'received' => true,
        'callback_id' => $pdo->lastInsertId()
    ];
    
} catch (Exception $e) {
    $response['error'] = $e->getMessage();
    http_response_code($e->getCode() ?: 400);
    
    // 记录错误日志
    error_log("Callback error: " . $e->getMessage());
}

echo json_encode($response);
?>
